package com.peas.platform.framework.mybatisplus.config;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.peas.platform.framework.mybatisplus.interceptor.CustomInterceptor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author caizhaohui
 */
@EnableTransactionManagement
@Configuration
public class MybatisPlusConfig {

    @Resource
    private ApplicationContext ac;
    @Resource
    private AlphaInnerInterceptor alphaInnerInterceptor;

    @Bean
    public CustomSqlInjector customizedSqlInjector() {
        return new CustomSqlInjector();
    }

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(optimisticLockerInnerInterceptor());
        interceptor.addInnerInterceptor(alphaInnerInterceptor);
        Map<String, CustomInterceptor> beans = ac.getBeansOfType(CustomInterceptor.class);
        CollUtil.forEach(beans, (CollUtil.KVConsumer<String, CustomInterceptor>) (key, value, index) -> interceptor.addInnerInterceptor(value));
        interceptor.addInnerInterceptor(paginationInnerInterceptor());
        return interceptor;
    }

    private PaginationInnerInterceptor paginationInnerInterceptor() {
        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor(DbType.MYSQL);
        // 设置请求的页面大于最大页后操作， true调回到首页，false 继续请求  默认false
        paginationInnerInterceptor.setOverflow(false);
        // 设置最大单页限制数量，默认 500 条，-1 不受限制
        paginationInnerInterceptor.setMaxLimit(500L);
        return paginationInnerInterceptor;
    }

    private OptimisticLockerInnerInterceptor optimisticLockerInnerInterceptor() {
        return new OptimisticLockerInnerInterceptor();
    }

}
